package org.linlinjava.litemall.admin.controller;


import com.alibaba.excel.EasyExcel;
import org.linlinjava.litemall.admin.beans.dto.GiftCardUserExcelEntity;
import org.linlinjava.litemall.admin.util.ExcelUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallGiftCard;
import org.linlinjava.litemall.db.domain.LitemallGiftCardUser;
import org.linlinjava.litemall.db.service.LitemallGiftCardService;
import org.linlinjava.litemall.db.service.LitemallGiftCardUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * excel导入控制器
 *
 * @author yliyun
 * @date 2022/09/14
 */
@RestController
@RequestMapping("/admin/easyExcel")
public class ExcelImportController {

    /**
     * exl文件路径
     */
    private String EXL_FILE_PATH = "导入礼物卡用户";

    /**
     * litemall礼品卡用户服务
     */
    @Autowired
    private LitemallGiftCardUserService litemallGiftCardUserService;

    /**
     * litemall礼品卡服务
     */
    @Autowired
    private LitemallGiftCardService litemallGiftCardService;

    /**
     * 导入客户日常
     *
     * @param file   文件
     * @param cardId 卡id
     * @return {@link Object}
     * @throws IOException ioexception
     */
    @PostMapping("/imports")
    @Transactional
    public Object importCustomerDaily(@RequestParam("file") MultipartFile file, @RequestParam Integer cardId) throws IOException {
        InputStream inputStream = file.getInputStream();
        List<GiftCardUserExcelEntity> entities = EasyExcel.read(inputStream)
                .head(GiftCardUserExcelEntity.class)
                // 设置sheet,默认读取第一个
                .sheet()
                // 设置标题所在行数
                .headRowNumber(1)
                .doReadSync();
        //List<GiftCardUserExcelEntity> entities1= entities.stream().distinct().collect(Collectors.toList());

        List<String> errors = new ArrayList<>();

        Stream.iterate(0, i -> i + 1).limit(entities.size()).forEach(index -> {

            LitemallGiftCardUser user = new LitemallGiftCardUser();
            BeanUtils.copyProperties(entities.get(index), user);
            user.setStatus(1);
            user.setIsDefault(0);

            Long l = litemallGiftCardUserService.sumByCardId(cardId);
            LitemallGiftCard card = litemallGiftCardService.findById(cardId);
            //TODO 错误的数据没有判断

            if(card.getNumbers()!=0&&(l.intValue()!=0&&card.getNumbers()-l<=0)) {
                errors.add("第" + index + "行数据由于礼物卡销售数量有限,没有成功插入数据");
            } else {
                //校验信用卡卡号
                String cardNo = entities.get(index).getCardNumber();
                if (cardNo.length() != 16) {
                    errors.add("第" + index + "行数据由于礼物卡不是16位数,没有成功插入数据");
                } else {
                    Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");
                    if (!pattern.matcher(cardNo).matches()) {
                        errors.add("第" + index + "行数据由于礼物卡不是纯数字,没有成功插入数据");
                    }
                }

                LitemallGiftCardUser cardUser = litemallGiftCardUserService.findByNumber(cardNo);
                if (cardUser != null) {
                    errors.add("第" + index + "行数据由于卡号已经存在,没有成功插入数据");
                } else {
                    user.setStatus(0);
                    user.setIsDefault(0);
                    user.setGiftCardId(cardId);
                    user.setCardNumber(cardNo);
                    user.setAmount(new BigDecimal(card.getAmount() != null ? card.getAmount() : 0));
                    litemallGiftCardUserService.add(user);
                }
            }
        });
        return errors.size() > 0?ResponseUtil.okList(errors):ResponseUtil.ok("导入成功");
    }

    /**
     * template2
     *
     * @param request  请求
     * @param response 响应
     *///    @ApiOperation(value = "下载模板文件测试-----该方法是测试使用")
    @GetMapping("/template2/gener")
    public void template2(HttpServletRequest request,HttpServletResponse response) {
        String fileName = "导入用户模板";
        String sheetName = "导入用户模板";
        List<GiftCardUserExcelEntity> userList = new ArrayList<>();
        try {
            ExcelUtil.writeExcel(response, userList, fileName, sheetName, GiftCardUserExcelEntity.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
